/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: liuzicheng
 * @Date: 2025-01-24 14:52:12
 * @LastEditors: liuzicheng
 * @LastEditTime: 2025-02-28 13:34:38
 */
import { Empty } from "antd";
import "moment/locale/zh-cn";
import { useEffect, useRef } from "react";
import VariableSizeList from "./VariableSizeList";
import { useNavigate } from "react-router";
function Item({ index, data, setHeight }: any) {
  const itemRef = useRef<any>();
  useEffect(() => {
    setHeight(index, itemRef.current.getBoundingClientRect().height);
  }, [setHeight, index]);

  return (
    <div
      ref={itemRef}
      style={{
        display: "flex",
        flexDirection: "column",
        justifyContent: "space-between",
        padding: "16px 0"
      }}
    >
      <div style={{ color: "rgba(0,0,0,0.85)" }}>{data[index]["title"]}</div>
      <div style={{ color: "rgba(0,0,0,0.45)" }}>{data[index]["sendTime"]}</div>
    </div>
  );
}

const MessageList = (props: any) => {
  const { list, containerHeight = 350 } = props;
  const history = useNavigate();
  const listRef = useRef<any>();
  const heightsRef = useRef(new Array(100));
  // 预估高度
  const estimatedItemHeight = 78;
  const getHeight = (index: number) => {
    return heightsRef.current[index] ?? estimatedItemHeight;
  };

  const setHeight = (index: number, height: number) => {
    if (heightsRef.current[index] !== height) {
      heightsRef.current[index] = height;
      // 让 VariableSizeList 组件更新高度
      listRef.current.resetHeight();
    }
  };
  return (
    <div style={{ width: "400px" }}>
      {list.length > 0 ? (
        <>
          <VariableSizeList
            ref={listRef}
            containerHeight={containerHeight}
            itemCount={list.length}
            getItemHeight={getHeight}
            itemData={list}
          >
            {({ index, style, data }: any) => {
              return (
                <div style={style}>
                  <Item {...{ index, data }} setHeight={setHeight} />
                </div>
              );
            }}
          </VariableSizeList>
        </>
      ) : (
        <Empty description="暂无未读消息" />
      )}
      <div
        style={{
          padding: "22px 0 10px",
          textAlign: "center",
          color: "#096DD9",
          cursor: "pointer"
        }}
        onClick={() => {
          history("/message");
          props?.hide();
        }}
      >
        查看全部消息
      </div>
    </div>
  );
};
export default MessageList;
